// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-16

package services

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"server/app/errs"
	"server/app/http/models"
	"server/app/kind"
)

// ListByIdList
// 按ID列表查询数据.
func (o *GoodsService) ListByIdList(ctx context.Context, conditions []kind.GoodsId) (list []*models.Goods, err error) {
	var sess *db.Session

	// 1. 获取连接.
	if sess, err = o.Dao.Slaver(ctx); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 主键查询.
	if err = sess.In("id", conditions).Find(&list); err != nil {
		err = errs.ErrDatabaseQuery
	}
	return
}

// MapByIdList
// 按ID列表查询数据.
func (o *GoodsService) MapByIdList(ctx context.Context, conditions []kind.GoodsId) (mapper map[kind.GoodsId]*models.Goods, err error) {
	var list []*models.Goods
	if list, err = o.ListByIdList(ctx, conditions); err == nil {
		mapper = make(map[kind.GoodsId]*models.Goods)
		for _, v := range list {
			mapper[v.Id] = v
		}
	}
	return
}

// Paging
// 商品分页.
func (o *GoodsService) Paging(ctx context.Context, data map[string]any, keyword string, page, size int) (list []*models.Goods, total int64, err error) {
	var (
		sess, s1, s2 *db.Session
	)
	if sess, err = o.Dao.Slaver(ctx); err == nil {
		s1 = sess.Where(data)
		if keyword != "" {
			s1.Where("name like ?", "%"+keyword+"%")
		}
		if total, err = s1.Count(models.Goods{}); err != nil || total == 0 {
			return
		}

		s2 = sess.Where(data)
		if keyword != "" {
			s2.Where("name like ?", "%"+keyword+"%")
		}
		err = s2.OrderBy("created_at DESC").Limit(size, (page-1)*size).Find(&list)
	}
	return
}
